package com.epfresh.wxapi;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.bean.OrderSuccess;
import com.alipay.sdk.app.PayTask;
import com.epfresh.R;
import com.epfresh.activity.OrderSuccessActivity;
import com.epfresh.activity.PayWaitActivity;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.L;
import com.epfresh.api.utils.ToastUtils;
import com.epfresh.bean.OrderPayWayListEntity;
import com.epfresh.global.BaseActivity;
import com.epfresh.wxapi.pay.alipay.PayResult;
import com.epfresh.wxapi.pay.weipay.Constants;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;


/*购物车   appOrder/accessPaymentPlatform"
* 支付按钮 appOrder/payWayList type=1
* 确认收货按钮   appOrder/payWayList type=2
* */
public class WXPayEntryActivity extends BaseActivity implements IWXAPIEventHandler {

    private View vRestMoney;

    private TextView tvRestMoney;
    OrderPayWayListEntity date;
    static final String TAG = "WXPayEntryActivity";
    String logisticsNo = "";

    String orderId="";
    private TextView order_name;
    private TextView order_money;
    private TextView money_time;
    private TextView pay_money;
    private ImageView select_money;
    private ImageView select_pos;
    private ImageView select_alipay;
    private ImageView select_weChat;
    private RelativeLayout item_alipay;
    private RelativeLayout item_weChat;
    private RelativeLayout item_unionPay;
    private RelativeLayout item_ccb;
    private RelativeLayout item_money;
    private RelativeLayout item_pos;
    private String type = "1";//列表支付1；确认收货过来是2
    private int payWayType = -1;//1:购物车；-1订单列表
    private int payWay = 1;

    private IWXAPI api;

    //购物车直接下单"appOrder/accessPaymentPlatform",物流单号"appOrder/payWayList"

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        if (savedInstanceState != null) {
            getIntent().putExtra("logisticsNo", savedInstanceState.getString("logisticsNo", ""));
            getIntent().putExtra("payWayType", savedInstanceState.getInt("payWayType"));
            getIntent().putExtra("payWay", savedInstanceState.getInt("payWay"));
            getIntent().putExtra("orderId", savedInstanceState.getString("orderId"));
            getIntent().putExtra("type", savedInstanceState.getString("type"));
            getIntent().putExtra("date", savedInstanceState.getSerializable("date"));
            if(null != savedInstanceState.getSerializable("date"))
                date = (OrderPayWayListEntity)savedInstanceState.getSerializable("date");
        }
        logisticsNo = getIntent().getStringExtra("logisticsNo");
        orderId = getIntent().getStringExtra("orderId");
        if(getIntent().getStringExtra("type")!=null) { //
            type = getIntent().getStringExtra("type");
        }
        payWayType = getIntent().getIntExtra("payWayType", -1);
        if (payWayType == 1) {  //该接口废弃，合并进 payWayList  type =1；
            //payCmd = "appOrder/accessPaymentPlatform";
            type="1";
        }
        mHttpLoad();
        initView();

        payWay = getIntent().getIntExtra("payWay", 1);

        if (payWay == 2) {
            vRestMoney.setVisibility(View.VISIBLE);
        }else{
            TextView tvInfoType = (TextView) findViewById(R.id.tv_info_type);
            tvInfoType.setText("需支付");
        }
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        api.handleIntent(getIntent(), this);
    }

    public boolean isWxInstall() {
        return api.isWXAppInstalled();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        api.handleIntent(getIntent(), this);
    }

    OnRequestListener<OrderPayWayListEntity> onRequestListener = new OnRequestListener<OrderPayWayListEntity>() {
        @Override
        public OrderPayWayListEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, OrderPayWayListEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            switch (failCode) {
                case HttpRequest.FAIL_NOT_FOUND:
                    // showReload();
                    break;
                case HttpRequest.FAIL_NO_NET:
                    toast(ApplicationHelper.getInstance().getDoc().getNetWeak());
                    break;
                case HttpRequest.FAIL_NET_FAULT:
                default:
                    toast(ApplicationHelper.getInstance().getDoc().getNetWeak());
                    break;
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            toast(arg + "");
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<OrderPayWayListEntity> response, Object tag) {
            OrderPayWayListEntity pay = response.getResponseElement();
            initModels(pay);
        }
    };

    private void mHttpLoad() {
        RequestEntityPurchase<Map<String, Object>> data = new RequestEntityPurchase<>();
        Map<String, Object> map = new HashMap<>();
        map.put("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        data.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_order_cash);
        if (payWayType == 1) {
            map.put("batchNo", logisticsNo);
        } else {
            map.put("orderId", orderId);
        }
        map.put("type", type);
        data.setParameters(map);
        request(data, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_order_cash, onRequestListener);
    }
    int walletType=0;
    void initModels(OrderPayWayListEntity response) {
        date = response;
        String title = response.getTitle();
        String money = response.getPayOnlineTotalValue();
        String unPayValue = response.getUnPayValue();
        totalFee = money == null || "".equals(money) ? "0" : money;
        tvRestMoney.setText(unPayValue + "元");
        order_money.setText(money + "元");
        TextView tvInfoType = (TextView) findViewById(R.id.tv_info_type);
        if(unPayValue!=null&&!unPayValue.equals("null")&&!unPayValue.equals("0.00")){
            vRestMoney.setVisibility(View.VISIBLE);
            tvInfoType.setText("需支付：订金");
        }else {
            tvInfoType.setText("需支付");
        }

        order_name.setText(title);
        if (type.equals("1")) {
            money_time.setVisibility(View.VISIBLE);
            int timeFlag = response.getPayRemainSeconds();
            if(timeFlag>0){
                getcodecontrol(timeFlag);//该处线程必须找到良好的关闭，以防止内存泄露！！！
            }else{
                pay_money.setBackgroundColor(getResources().getColor(R.color.TextColorlight));
                pay_money.setClickable(false);
                money_time.setText("支付已超时");
            }
        } else {
            View ll_pay_time = findViewById(R.id.ll_pay_time);
            ll_pay_time.setVisibility(View.GONE);
            money_time.setVisibility(View.GONE);
        }

        walletType = response.getType();
        String walletTitle = response.getWalletsTitle();
        String walletNumber = response.getWallets()+"元";
        TextView tvWalletTitle = (TextView) findViewById(R.id.tv_wallet);
        TextView tvWalletNumber = (TextView) findViewById(R.id.tv_wallet_number);

        findViewById(R.id.rl_wallet).setVisibility(response.isWalletsInVisible()?View.GONE:View.VISIBLE);
        tvWalletNumber.setText(walletNumber);
        tvWalletTitle.setText(walletTitle);
        if(walletType!=0){
            item_weChat.setBackgroundColor(Color.parseColor("#fcfcfc"));
            item_alipay.setBackgroundColor(Color.parseColor("#fcfcfc"));
            select_alipay.setVisibility(View.GONE);
            select_weChat.setVisibility(View.GONE);
            item_alipay.setClickable(false);
            item_weChat.setClickable(false);
        }

    }

    private void initView() {
        setContentView(R.layout.activity_pay_list_0);
        order_name = (TextView) findViewById(R.id.order_name);
        order_money = (TextView) findViewById(R.id.order_money);
        pay_money = (TextView) findViewById(R.id.pay_money);
        money_time = (TextView) findViewById(R.id.money_time);

        select_money = (ImageView) findViewById(R.id.select_money);
        select_pos = (ImageView) findViewById(R.id.select_pos);
        select_alipay = (ImageView) findViewById(R.id.select_alipay);
        select_weChat = (ImageView) findViewById(R.id.select_weChat);


        item_alipay = (RelativeLayout) findViewById(R.id.item_alipay);
        item_weChat = (RelativeLayout) findViewById(R.id.item_weChat);
        item_unionPay = (RelativeLayout) findViewById(R.id.item_unionPay);
        item_ccb = (RelativeLayout) findViewById(R.id.item_ccb);
        item_money = (RelativeLayout) findViewById(R.id.item_money);
        item_pos = (RelativeLayout) findViewById(R.id.item_pos);

        baseback.setVisibility(View.VISIBLE);
        basetitle.setText("收银台");
        pay_money.setOnClickListener(this);
        item_alipay.setOnClickListener(this);
        item_weChat.setOnClickListener(this);
        item_unionPay.setOnClickListener(this);
        item_ccb.setOnClickListener(this);
        item_pos.setOnClickListener(this);
        item_money.setOnClickListener(this);
        vRestMoney = findViewById(R.id.ll_rest_money);
        tvRestMoney = (TextView) findViewById(R.id.tv_rest_money);
    }

    boolean payOnline = true;
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pay_money:
                if (payOnline == true) {
                    mHttpLoadPay();
                }
                break;
            case R.id.baseback:
                // 返回上一页
                new AlertDialog.Builder(mContext).setTitle("确定离开？")//设置对话框标题
                        .setMessage("您尚未完成订单支付，请确认是否继续支付或稍后再支付？")//设置显示的内容
                        .setPositiveButton("离开", new DialogInterface.OnClickListener() {//添加确定按钮
                            @Override
                            public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
/*                                Intent detail = new Intent(mContext, DetailOrderActivity.class);todo
                                detail.putExtra("id", orderId);
                                detail.putExtra("flag", "NEWORDER");
                                startActivity(detail);*/
                                finish();
                            }
                        }).setNegativeButton("继续支付", new DialogInterface.OnClickListener() {//添加返回按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//响应事件
                        // TODO Auto-generated method stub
                    }

                }).show();//在按键响应事件中显示此对话框
                //finish();
                break;
            case R.id.item_ccb:
            case R.id.item_unionPay:
                ToastUtils.ImageToast(mContext, R.mipmap.login_04, "此种支付方式暂未开通");
                break;
            case R.id.item_weChat:
                cmd = AppPurchaseRouterConstant.cmd_finance_payment_weChat;
                select_weChat.setImageResource(R.drawable.register_unread);
                select_alipay.setImageResource(R.drawable.register_unread);
                select_money.setImageResource(R.drawable.register_unread);
                select_pos.setImageResource(R.drawable.register_unread);
                select_weChat.setImageResource(R.drawable.select_round);
                payOnline = true;
                if (AppPurchaseRouterConstant.cmd_finance_payment_weChat.equals(cmd) && !isWxInstall()) {
                    toast("没有安装微信");
                }
                break;
            case R.id.item_alipay:
                cmd = AppPurchaseRouterConstant.cmd_finance_payment_alipay;
                select_weChat.setImageResource(R.drawable.register_unread);
                select_alipay.setImageResource(R.drawable.register_unread);
                select_money.setImageResource(R.drawable.register_unread);
                select_pos.setImageResource(R.drawable.register_unread);
                select_alipay.setImageResource(R.drawable.select_round);
                payOnline = true;
                break;
            case R.id.item_pos:
                select_weChat.setImageResource(R.drawable.register_unread);
                select_alipay.setImageResource(R.drawable.register_unread);
                select_money.setImageResource(R.drawable.register_unread);
                select_pos.setImageResource(R.drawable.register_unread);
                select_pos.setImageResource(R.drawable.select_round);
                payOnline = false;

                break;
            case R.id.item_money:
                select_weChat.setImageResource(R.drawable.register_unread);
                select_alipay.setImageResource(R.drawable.register_unread);
                select_money.setImageResource(R.drawable.register_unread);
                select_pos.setImageResource(R.drawable.register_unread);
                select_money.setImageResource(R.drawable.select_round);
                payOnline = false;
                break;
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            new AlertDialog.Builder(mContext).setTitle("确定离开？")//设置对话框标题
                    .setMessage("您尚未完成订单支付，请确认是否继续支付或稍后再支付？")//设置显示的内容
                    .setPositiveButton("离开", new DialogInterface.OnClickListener() {//添加确定按钮
                        @Override
                        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
/*                            Intent detail = new Intent(mContext, DetailOrderActivity.class);todo
                            detail.putExtra("id", orderId);
                            detail.putExtra("flag", "NEWORDER");
                            startActivity(detail);*/
                            finish();
                        }
                    }).setNegativeButton("继续支付", new DialogInterface.OnClickListener() {//添加返回按钮
                @Override
                public void onClick(DialogInterface dialog, int which) {//响应事件
                    // TODO Auto-generated method stub
                }

            }).show();//在按键响应事件中显示此对话框
        }
        return false;
    }

    String totalFee = "0";
    String cmd = AppPurchaseRouterConstant.cmd_finance_payment_alipay;

    private void mHttpLoadPay() {
        final RequestEntityPurchase<Map<String, Object>> data = new RequestEntityPurchase<>();
        Map<String, Object> map = new HashMap<>();

        if(walletType!=0){
            data.setCmd(AppPurchaseRouterConstant.cmd_order_order_walletsPaidSuccess);
            if (payWayType == 1) {//1 购物车？ -1列表  提交订单时orderIds传null，列表中支付时 batchNo传空
                map.put("batchNo", logisticsNo);
            }
            if(getIntent().getStringExtra("orderId")!=null){
                map.put("orderId",getIntent().getStringExtra("orderId"));
            }
            map.put("payWallets",date.getPayWallets());
            map.put("accountId",getUser().getAccountId());
            map.put("type",type);
            data.setParameters(map);
            request(data, AppPurchaseRouterConstant.cmd_order_order_walletsPaidSuccess, new OnRequestListener<String>() {
                @Override
                public String jsonToObj(String responseStr) {
                    Log.i("responseStr+++++++++++", responseStr);
                    return responseStr;

                }

                @Override
                public void onFail(int failCode, Object arg, Object tag) {
                    pay_money.setEnabled(true);
                }

                @Override
                public void onResponseError(int failCode, Object arg, Object tag) {
                    pay_money.setEnabled(true);
                }

                @Override
                public void onStart(Object tag) {
                    pay_money.setEnabled(false);
                }
                @Override
                public void onResponse(ResponseEntity<String> res, Object tag) {
                    Toast.makeText(mContext, "下单成功", Toast.LENGTH_SHORT).show();
                    //Intent success = new Intent(mContext, OrderSuccessActivity.class);
                    Intent success = new Intent(mContext, OrderSuccessActivity.class);
//                    success.putExtra("id", orderId);
                    success.putExtra("factSum", date.getPayOnlineTotalValue());
                    success.putExtra("wallets", date.getPayWallets());
                    success.putExtra("noPay",date.getUnPayValue());
                    success.putExtra("onLinePay",date.getPayOnlineValue());
                    startActivity(success);
                    finish();
                }
            });
            return;
        }


        if (AppPurchaseRouterConstant.cmd_finance_payment_weChat.equals(cmd) && !isWxInstall()) {
            toast("没有安装微信");
            return;
        }
        data.setCmd(cmd);
        //    String orderId="114763", logisticsNo="1260721365651";
//        map.put("orderId", orderId);
        if (payWayType == 1) {
            map.put("batchNo", logisticsNo);
        }else {
            map.put("orderId", orderId);
        }
        data.setParameters(map);
        request(data, cmd, new OnRequestListener<String>() {
            @Override
            public String jsonToObj(String responseStr) {
                Log.i("responseStr+++++++++++", responseStr);
                return responseStr;

            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                pay_money.setEnabled(true);
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                pay_money.setEnabled(true);
            }

            @Override
            public void onStart(Object tag) {
                pay_money.setEnabled(false);
            }

            /*
            _input_charset=\"utf-8\"&body=\"111\"&it_b_pay=\"30m\"&notify_url=\"http://api.epfresh.com/payment/aliPay/notify\"&out_trade_no=\"20160805005824108500\"&partner=\"2088121355233724\"&payment_type=\"1\"&seller_id=\"365.pay@cesgroup.com.cn\"&service=\"mobile.securitypay.pay\"&sign=\"jyJf24oLlWYYsk1%2BjfpBEpih%2FQPWbUvOGKUvb314ZhyfAcYO4mTiRM%2Bsymye%2Fpv%2BwgAv60wEQMEA3s%2F9rJJ3hm2%2Fb%2BdOf0IbcZsrmiYPzu2eYlCxms4z%2Bmejj2otSgD4JhVGAYKVo7AMiXvOk1ATJC%2FJXbu6JXolmx0MZz9siMo%3D\"&sign_type=\"RSA\"&subject=\"e批生鲜-订单支付：0031160802540327\"&total_fee=\"0.01\"
            * */
            @Override
            public void onResponse(ResponseEntity<String> res, Object tag) {
                String resString = res.getResponseElement();
                pay_money.setEnabled(true);
                Log.i("resString______________", resString);
                if (cmd.equals(AppPurchaseRouterConstant.cmd_finance_payment_alipay)) {
                    aliPay(resString);
                    return;
                } else if (cmd.equals(AppPurchaseRouterConstant.cmd_finance_payment_weChat)) {
                    wePay(resString);
                    return;
                }
            }
        });
    }

    private void aliPay(String res) {
        String aliPayParam = "";
        try {
            JSONObject response = new JSONObject(res);
            JSONObject info = response.getJSONObject("orderInfo");
            totalFee = info.getString("totalFee");
            aliPayParam = response.getString("aliPayParam");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        final String payInfo = aliPayParam;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(WXPayEntryActivity.this);
                // 调用支付接口，获取支付结果
                Log.i("payInfo:", payInfo);
                String result = alipay.pay(payInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                Log.i("result", result.toString());
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();


    }

    private void wePay(String response) {
        IWXAPI api;
        PayReq request = new PayReq();

        try {
            JSONObject all = new JSONObject(response);
            JSONObject weChat = all.getJSONObject("weChat");
            request.appId = weChat.getString("appid");
            request.partnerId = weChat.getString("partnerid");
            request.prepayId = weChat.getString("prepayid");
            request.packageValue = weChat.getString("package");
            //requestDc.packageValue = "com.epfresh";
            request.nonceStr = weChat.getString("noncestr");
            request.timeStamp = weChat.getString("timestamp");
            request.sign = weChat.getString("sign");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        api = WXAPIFactory.createWXAPI(WXPayEntryActivity.this, "wx724dc919a827351d", false);
        api.registerApp("wx724dc919a827351d");
        api.sendReq(request);
        Log.d("wezhifu", "wx724dc919a827351d");
    }

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    Log.i("payResult", payResult.toString());

                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息


                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    //9000	订单支付成功
                    //8000	正在处理中
                    //4000	订单支付失败
                    //6001	用户中途取消
                    //6002	网络连接出错
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(mContext, "支付成功", Toast.LENGTH_SHORT).show();
                        //Intent success = new Intent(mContext, OrderSuccessActivity.class);


                        mLastParametersLoad();


/*                      Intent success = new Intent(mContext, PayWaitActivity.class);//当前做更改，微信和支付宝支付下单成功后，先调一次服务器支付数据，然后再跳转！
                        success.putExtra("factSum", date.getPayOnlineTotalValue());
                        success.putExtra("wallets", date.getPayWallets());
                        success.putExtra("noPay",date.getUnPayValue());
                        success.putExtra("onLinePay",date.getPayOnlineValue());
                        startActivity(success);
                        finish();*/
                    } else if ("8000".equals(resultStatus)) {
                        Toast.makeText(mContext, "正在处理中", Toast.LENGTH_SHORT).show();
                    } else if ("4000".equals(resultStatus)) {
                        Toast.makeText(mContext, "订单支付失败", Toast.LENGTH_SHORT).show();
                    } else if ("6001".equals(resultStatus)) {
//                        Toast.makeText(mContext, "取消支付", Toast.LENGTH_SHORT).show();
                    } else if ("6002".equals(resultStatus)) {
                        Toast.makeText(mContext, "网络连接出错", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(mContext, "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
                case 0:
                   /* if (loadNoticeDialog != null)
                        loadNoticeDialog.dismiss();*/
                    Object o = msg.obj;
                    String result = "支付成功";
                    if (o != null) {
                        result = (String) o;
                    }
                    Toast.makeText(mContext, result, Toast.LENGTH_SHORT).show();
                    mLastParametersLoad();
                    //Intent success = new Intent(mContext, OrderSuccessActivity.class);
/*                    Intent success = new Intent(mContext, OrderSuccessActivity.class);///////////////
//                    success.putExtra("id", orderId);
                    success.putExtra("factSum", date.getPayOnlineTotalValue());
                    success.putExtra("wallets", date.getPayWallets());
                    success.putExtra("noPay",date.getUnPayValue());
                    success.putExtra("onLinePay",date.getPayOnlineValue());
                    startActivity(success);
                    finish();*/
                    break;
                case -1:
                   /* if (loadNoticeDialog != null)
                        loadNoticeDialog.dismiss();*/
                    Object o1 = msg.obj;
                    String result1 = "支付失败";
                    if (o1 != null) {
                        result1 = (String) o1;
                    }
                    Toast.makeText(mContext, result1, Toast.LENGTH_SHORT).show();
                    break;
                case -2:
                  /*  if (loadNoticeDialog != null)
                        loadNoticeDialog.dismiss();*/
                    Object o2 = msg.obj;
                    String result2 = "取消支付";
                    if (o2 != null) {
                        result = (String) o2;
                    }
                    Toast.makeText(mContext, result2, Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }

    };


    /**
     * 获取支付倒计时控制
     */
    private void getcodecontrol(final int time) {
        new Thread() {
            public void run() {

                for (int i = time; i >= 0; i--) {
                    Message message = Message.obtain();
                    message.arg1 = i;
                    handler.sendMessage(message);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

        }.start();

    }

    String timeFlag = "";
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            int i = msg.arg1;
            if (i > 60) {
                timeFlag = "(" + i / 60 + "分" + i % 60 + "秒" + ")";
            } else if (i >= 1 && i <= 60) {
                timeFlag = "(" + i + "秒" + ")";
            } else {
                timeFlag = "";
                pay_money.setBackgroundColor(getResources().getColor(R.color.TextColorlight));
                pay_money.setClickable(false);
                money_time.setText("支付已超时");
                return;
            }
            money_time.setText("剩余支付时间  " + timeFlag);
//			pay_money.setClickable(true);

        }

    };

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("logisticsNo", logisticsNo);
        outState.putInt("payWayType", payWayType);
        outState.putInt("payWay", payWay);
        outState.putString("orderId", orderId);
        outState.putString("type",type);
        if(null != date)
            outState.putSerializable("date",date);
    }

    @Override
    public void onReq(BaseReq baseReq) {
        L.d("wx", "onreq:" + SystemClock.currentThreadTimeMillis() + "");
    }

    @Override
    public void onResp(BaseResp resp) {
        L.d("wx", "onresp:" + SystemClock.currentThreadTimeMillis() + "");
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            if (resp.errCode == 0) {
                mLastParametersLoad();
/*                Intent success = new Intent(mContext, OrderSuccessActivity.class);
//                success.putExtra("id", orderId);
                success.putExtra("factSum", date.getPayOnlineTotalValue());
                success.putExtra("wallets", date.getPayWallets());
                success.putExtra("noPay",date.getUnPayValue());
                success.putExtra("onLinePay",date.getPayOnlineValue());
                startActivity(success);
                finish();*/
            } else if (resp.errCode == -2) {
//                Toast.makeText(mContext, "取消支付", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(mContext, "支付失败", Toast.LENGTH_SHORT).show();

            }
        }
    }

    private void mLastParametersLoad() {
        RequestEntityPurchase<Map<String, Object>> data = new RequestEntityPurchase<>();
        Map<String, Object> map = new HashMap<>();
        data.setCmd(AppPurchaseRouterConstant.cmd_order_order_paidSuccessInfo);
        if (payWayType == 1) {
            map.put("batchNo", logisticsNo);
        } else {
            map.put("orderId", orderId);
        }
        map.put("type",""+type );
        map.put("payWallets", date.getPayWallets());
        data.setParameters(map);
        request(data, AppPurchaseRouterConstant.cmd_order_order_paidSuccessInfo, lastParametersListener);
    }

    OnRequestListener<com.epfresh.bean.OrderSuccess> lastParametersListener = new OnRequestListener<OrderSuccess>() {
        @Override
        public OrderSuccess jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, OrderSuccess.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            switch (failCode) {
                case HttpRequest.FAIL_NOT_FOUND:
                    // showReload();
                    break;
                case HttpRequest.FAIL_NO_NET:
                    toast(ApplicationHelper.getInstance().getDoc().getNetWeak());
                    break;
                case HttpRequest.FAIL_NET_FAULT:
                default:
                    toast(ApplicationHelper.getInstance().getDoc().getNetWeak());
                    break;
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            toast(arg + "");
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<OrderSuccess> response, Object tag) {
            OrderSuccess detail = response.getResponseElement();
            if(detail.isSuccess()){
                if(AppPurchaseRouterConstant.cmd_finance_payment_weChat.equals(cmd)){
                    Intent success = new Intent(mContext, PayWaitActivity.class);//当前做更改，微信和支付宝支付下单成功后，先调一次服务器支付数据，然后再跳转！
                    success.putExtra("factSum", detail.getPayAllMoney());
                    success.putExtra("wallets", date.getPayWallets());
                    success.putExtra("noPay",date.getUnPayValue());
                    success.putExtra("onLinePay",date.getPayOnlineValue());
                    startActivity(success);
                    finish();
                }else {
                    Intent success = new Intent(mContext, OrderSuccessActivity.class);
//                    success.putExtra("id", orderId);
                    success.putExtra("factSum", detail.getPayAllMoney());
                    success.putExtra("wallets", date.getPayWallets());
                    success.putExtra("noPay",date.getUnPayValue());
                    success.putExtra("onLinePay",date.getPayOnlineValue());
                    startActivity(success);
                    finish();
                }


            }
        }
    };


}
